
#include "net.h"

size_t save_sina_page(void *buffer, size_t size, size_t count, void *user_p)
{
	log_i("size:%d\n",size*count);	

	return fwrite(buffer, size, count, (FILE *)user_p);
}

size_t save_sohu_page(void *buffer, size_t size, size_t count, void *user_p)
{
    return size*count;
}


int net_multi_download(const char *ip_str,const char * localpath)
{
    // 初始化
    curl_global_init(CURL_GLOBAL_WIN32);
    CURLM *multi_handle = NULL;
    CURL *easy_handle1 = NULL;
	

    FILE *fp_sina = fopen(localpath, "ab+");

    multi_handle = curl_multi_init();

    // 设置easy handle
    easy_handle1 = curl_easy_init();
    curl_easy_setopt(easy_handle1, CURLOPT_URL, ip_str);
    curl_easy_setopt(easy_handle1, CURLOPT_WRITEFUNCTION, &save_sina_page);
    curl_easy_setopt(easy_handle1, CURLOPT_WRITEDATA, fp_sina);


    // 添加到multi stack
    curl_multi_add_handle(multi_handle, easy_handle1);

	log_i("curl multi succeed.\n");

    int running_handle_count;
    while (CURLM_CALL_MULTI_PERFORM == curl_multi_perform(multi_handle, &running_handle_count))
    {
		log_e("running_handle_count:%d\n",running_handle_count);	
    }

    while (running_handle_count)
    {
        struct timeval tv;
        tv.tv_sec = 1;
        tv.tv_usec = 0;

        int max_fd;
        fd_set fd_read;
        fd_set fd_write;
        fd_set fd_except;

        FD_ZERO(&fd_read);
        FD_ZERO(&fd_write);
        FD_ZERO(&fd_except);

        curl_multi_fdset(multi_handle, &fd_read, &fd_write, &fd_except, &max_fd);
        int return_code = select(max_fd + 1, &fd_read, &fd_write, &fd_except, &tv);
        if (-1 == return_code)
        {
			log_e("http download end:%d:%s\n",return_code, curl_easy_strerror(return_code));	
            break;
        }
        else
        {
            while (CURLM_CALL_MULTI_PERFORM == curl_multi_perform(multi_handle, &running_handle_count))
            {
				log_e("running_handle_count:%d\n",running_handle_count);	
            }
        }
    }

    // 释放资源
    fclose(fp_sina);
    curl_easy_cleanup(easy_handle1);
    curl_multi_cleanup(multi_handle);
    curl_global_cleanup();

    return 0;
}



